﻿using chatSDKApp.ChatRoom;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Xml;

namespace chatSDKApp
{
    public partial class FrmLogin : Form
    {
        #region 私有变量
        /// <summary>
        /// 进度条线程对象
        /// </summary>
        private BackgroundWorker _worker = null;

        /// <summary>
        /// 主窗口
        /// </summary>
        private FrmChatRoom _mainForm = null;


        #endregion


        #region 重构comboBox1控件  添加删除功能  变量

        [DllImport("user32")]
        private static extern int GetComboBoxInfo(IntPtr hwnd, out COMBOBOXINFO comboInfo);
        struct RECT
        {
            public int left, top, right, bottom;
        }
        struct COMBOBOXINFO
        {
            public int cbSize;
            public RECT rcItem;
            public RECT rcButton;
            public int stateButton;
            public IntPtr hwndCombo;
            public IntPtr hwndItem;
            public IntPtr hwndList;
        }
        bool combox;
        IntPtr hwnd;
        NativeCombo nativeCombo = new NativeCombo();
        //This is to store the Rectangle info of your Icons
        //Key:  the Item index
        //Value: the Rectangle of the Icon of the item (not the Rectangle of the item)
        Dictionary<int, Rectangle> dict = new Dictionary<int, Rectangle>();
        public class NativeCombo : NativeWindow
        {
            //this is custom MouseDown event to hook into later
            public event MouseEventHandler MouseDown;
            protected override void WndProc(ref Message m)
            {
                if (m.Msg == 0x201)//WM_LBUTTONDOWN = 0x201
                {
                    int x = m.LParam.ToInt32() & 0x00ff;
                    int y = m.LParam.ToInt32() >> 16;
                    if (MouseDown != null) MouseDown(null, new MouseEventArgs(MouseButtons.Left, 1, x, y, 0));
                }
                base.WndProc(ref m);
            }
        }

        #endregion


        #region 构造方法
        public FrmLogin()
        {
            InitializeComponent();

            #region 重构comboBox1控件  所需数据
            cboUserName.HandleCreated += (s, e) =>
            {
                COMBOBOXINFO combo = new COMBOBOXINFO();
                combo.cbSize = Marshal.SizeOf(combo);
                GetComboBoxInfo(cboUserName.Handle, out combo);
                hwnd = combo.hwndList;
                combox = false;
            };
            #endregion

            Control.CheckForIllegalCrossThreadCalls = false;
        }

        public FrmLogin(FrmChatRoom frmMain)
            : this()
        {
            this._mainForm = frmMain;
        }

        #endregion


        #region 私有方法

        #region 初始化数据
        #endregion

        #region 私有辅助方法
        /// <summary>
        /// 获取进度信息
        /// </summary>
        /// <param name="progress"></param>
        /// <param name="stepLen"></param>
        /// <returns></returns>
        private float GetProgress(float progress, float stepLen)
        {
            progress += stepLen;
            if (progress > 100)
                progress = 100;

            return progress;
        }

        #endregion


        #endregion

        #region 事件处理

        #region 滚动条事件
        //处理程序中可以得到异步处理结果信息
        void _worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error == null && (bool)e.Result == true)
            {
                this.Cursor = Cursors.Default;
                this.DialogResult = DialogResult.OK;
                btnOK.Enabled = true;
            }
        }

        //通过调用worker.ReportProgress方法触发ProgressChanged事件，接着通过ProgressChanged事件处理程序来更新进度显示。
        void _worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            Invoke((Action)delegate
           {
               this.progressBar1.Value = e.ProgressPercentage;
               this.labPercentage.Text = e.ProgressPercentage + "%";
               this.labStatus.Text = e.UserState.ToString();
               labStatus.Left = Width / 2 - labStatus.Width / 2;
               this.labPercentage.Update();
           });
        }

        #endregion

        #region 界面按钮事件

        #region 取消
        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            Application.Exit();
        }
        #endregion

        #region 登录
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.cboUserName.Text))
            {
                MessageBox.Show("用户名不能为空", "提示信息");
                return;
            }

            if (string.IsNullOrWhiteSpace(this.txtPassword.Text))
            {
                MessageBox.Show("密码不能为空", "提示信息");
                return;
            }

         
            try
            {
               

            }
            catch (Exception ex)
            {
                btnOK.Enabled = true;
                LogHelper.Log("登录失败", ex.ToString());
                MessageBox.Show(@"登录失败，请重试！", @"登录失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #endregion

        #endregion

        #region 重写方法 为窗口拖动服务

        [DllImport("user32.dll")]
        public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wparam, int lparam);

        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            if (e.Button == MouseButtons.Left)//按下的是鼠标左键            
            {
                Capture = false;//释放鼠标，使能够手动操作                
                SendMessage(Handle, 0x00A1, 2, 0);//拖动窗体            
            }
        }

        #endregion

        #region 用户名密码辅助方法

      
        #endregion

        #region 重绘窗口文字
        private void FrmLogin_Paint(object sender, PaintEventArgs e)
        {
            DrawString(e.Graphics, "环信IM通讯", Color.FromArgb(33, 122, 166), new System.Drawing.PointF(15, 80), true, true);

            DrawString(e.Graphics, "通讯客户端", Color.FromArgb(180, 204, 231), new System.Drawing.PointF(200, 130), false, true);

        }

        /// <summary>
        /// 绘制字符
        /// </summary>
        /// <param name="g">GDI+ 绘图</param>
        /// <param name="text">文字</param>
        /// <param name="fontColor">文字颜色</param>
        /// <param name="point">起始坐标</param>
        /// <param name="isGradient">是否滤境</param>
        /// <param name="isBackColor">是否是背景</param>
        public void DrawString(Graphics g, string text, Color fontColor, PointF point, bool isGradient, bool isBackColor)
        {
            Brush backBrush = Brushes.Black;
            Font font = new Font("华文行楷", System.Convert.ToInt16(28), FontStyle.Regular);
            SizeF size = g.MeasureString(text, font);
            Rectangle rectangle = new System.Drawing.Rectangle
            {
                X = (int)point.X,
                Y = (int)point.Y,
                Width = (int)size.Width,
                Height = (int)size.Height
            };
            //滤境效果
            Brush brush;
            if (isGradient)
                brush = new LinearGradientBrush(rectangle, Color.White, fontColor, LinearGradientMode.Vertical);
            else
                brush = new SolidBrush(fontColor);
            Single posX = (this.Width - Convert.ToInt16(size.Width)) / 2;
            Single posY = (this.Height - Convert.ToInt16(size.Height)) / 3;
            if (isBackColor)
            {
                int i = 0;
                while (i < Convert.ToInt16(5))
                {
                    g.DrawString(text, font, backBrush, point.X - i, point.Y + i);
                    i = i + 1;
                }
            }
            g.DrawString(text, font, brush, point);
        }
        #endregion


        #region 重构下拉框数据
        private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index > -1)
            {
                if ((e.State & DrawItemState.Selected) != 0)//鼠标选中在这个项上
                {
                    // 渐变画刷
                    LinearGradientBrush brush = new LinearGradientBrush(e.Bounds, Color.FromArgb(0, 120, 215),
                        Color.FromArgb(0, 120, 215), LinearGradientMode.Vertical);
                    //填充区域
                    Rectangle borderRect = new Rectangle(0, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height - 2);
                    e.Graphics.FillRectangle(brush, borderRect);
                    //画边框
                    Pen pen = new Pen(Color.FromArgb(0, 120, 215));
                    e.Graphics.DrawRectangle(pen, borderRect);
                }
                else
                {
                    SolidBrush brush = new SolidBrush(Color.FromArgb(255, 255, 255));
                    e.Graphics.FillRectangle(brush, e.Bounds);
                }
                //获得项图片,绘制图片
                // comboItem item = (comboItem)comboBox1.Items[e.Index];
                Image img = Image.FromFile(Application.StartupPath + "\\Images\\del.png");

                //图片绘制的区域
                Rectangle imgRect = new Rectangle(e.Bounds.Width - 18, e.Bounds.Y, 15, 15);
                dict[e.Index] = imgRect;
                if (img != null && (e.State & DrawItemState.Selected) != 0)
                {
                    e.Graphics.DrawImage(img, imgRect);

                }
                Rectangle textRect =
                    new Rectangle(0, imgRect.Y, e.Bounds.Width - imgRect.Width, e.Bounds.Height + 2);
                // string itemText = comboBox1.Items[e.Index].ToString();
                string itemText = cboUserName.Items[e.Index].GetType().GetProperty("UserCode").GetValue(cboUserName.Items[e.Index], null).ToString();
                StringFormat strFormat = new StringFormat();
                strFormat.LineAlignment = StringAlignment.Center;
                e.Graphics.DrawString(itemText, new Font("宋体", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))), Brushes.Black, textRect, strFormat);

            }
        }


        private void comboBox1_DropDown(object sender, EventArgs e)
        {
            if (!combox)
            {
                //Register the MouseDown event handler <--- THIS is WHAT you want.
                nativeCombo.MouseDown += comboListMouseDown;
                nativeCombo.AssignHandle(hwnd);
                combox = true;
            }
        }

        private void comboListMouseDown(object sender, MouseEventArgs e)
        {
            
        }

        #endregion

        private void llab_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
     
        }

        private void cbLine_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }
    }
}
